<template>
  <div class="customer-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" :icon="Plus">新增顾客</el-button>
      <el-input
        v-model="searchKey"
        placeholder="搜索顾客姓名/身份证号"
        class="search-input"
        :prefix-icon="Search"
        clearable
      />
    </div>

    <!-- 顾客列表 -->
    <el-card class="table-card" v-loading="loading">
      <el-table 
        :data="paginatedCustomerList" 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        border>
        <el-table-column prop="customerId" label="顾客ID" width="100" align="center" />
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="idNumber" label="身份证号" width="180" align="center" />
        <el-table-column prop="work" label="工作单位" min-width="180" align="center" />
        <el-table-column prop="occupation" label="职位" width="150" align="center" />
        <el-table-column prop="routeName" label="旅游信息" min-width="180" align="center">
          <template #default="scope">
            <el-tag type="success" effect="plain" v-if="scope.row.routeName">
              {{ scope.row.routeName }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 在表格下方添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredCustomerList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 新增顾客对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增顾客"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-form
        ref="formRef"
        :model="customerForm"
        :rules="rules"
        label-width="100px"
        class="custom-form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="customerForm.name" placeholder="请输入顾客姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="customerForm.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="工作单位" prop="work">
          <el-input v-model="customerForm.work" placeholder="请输入工作单位" />
        </el-form-item>
        <el-form-item label="职位" prop="occupation">
          <el-input v-model="customerForm.occupation" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="旅游信息" prop="travelId">
          <el-popover
            placement="right"
            :width="400"
            trigger="click"
            v-model:visible="popoverVisible"
            popper-class="travel-info-popover">
            <template #reference>
              <el-input
                v-model="selectedTravelName"
                placeholder="点击选择旅游信息"
                readonly
                :suffix-icon="ArrowDown"
                class="travel-selector"
              />
            </template>
            
            <!-- 旅游信息选择面板 -->
            <div class="travel-options">
              <div class="travel-search">
                <el-input
                  v-model="travelSearchKey"
                  placeholder="搜索线路名称"
                  :prefix-icon="Search"
                  clearable
                />
              </div>
              <div class="travel-list">
                <div
                  v-for="option in filteredTravelOptions"
                  :key="option.travelId"
                  class="travel-item"
                  :class="{ 'is-selected': customerForm.travelId === option.travelId }"
                  @click="selectTravel(option)">
                  <div class="travel-header">
                    <span class="travel-name">{{ option.routeName }}</span>
                    <el-tag size="small" type="success">¥{{ option.money }}</el-tag>
                  </div>
                  <div class="travel-info-row">
                    <el-tag size="small" type="info" class="guide-tag">导游等级: {{ option.guideLevel }}级</el-tag>
                    <span class="travel-time">{{ option.travelStartTime }} 至 {{ option.travelEndTime }}</span>
                  </div>
                  <div class="travel-spots">
                    <span class="label">景点：</span>
                    <span class="content">{{ option.message }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Search, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { customerApi } from '@/api'

// 接口定义
interface TravelMessageVo {
  travelId: number
  routeName: string
  guideLevel: number
  message: string
  money: number
  travelStartTime: string
  travelEndTime: string
}

interface CustomerResponseVo {
  customerId: number
  name: string
  idNumber: string
  work: string
  occupation: string
  travelId: number
  routeName: string
}

// 数据定义
const customerList = ref<CustomerResponseVo[]>([])
const routeOptions = ref<TravelMessageVo[]>([])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const searchKey = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 表单数据
const customerForm = ref({
  name: '',
  idNumber: '',
  work: '',
  occupation: '',
  travelId: undefined as number | undefined
})

// 表单校验规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入顾客姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  work: [{ required: true, message: '请输入工作单位', trigger: 'blur' }],
  occupation: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  travelId: [{ required: true, message: '请选择旅游线路', trigger: 'change' }]
})

// 搜索过滤
const filteredCustomerList = computed(() => {
  if (!searchKey.value) return customerList.value
  return customerList.value.filter(item => 
    item.name.includes(searchKey.value) || 
    item.idNumber.includes(searchKey.value)
  )
})

// 修改分页计算属性
const paginatedCustomerList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  // 先反转数组，再进行分页
  return [...filteredCustomerList.value].reverse().slice(start, end)
})

// 添加 loading ref
const loading = ref(false)

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await customerApi.getAllCustomers()
    customerList.value = res??[]
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取线路选项
const fetchRouteOptions = async () => {
  loading.value = true
  try {
    const res = await customerApi.getTravelInfo()
    routeOptions.value = res??[]
  } catch (error) {
    ElMessage.error('获取线路数据失败')
  } finally {
    loading.value = false
  }
}

// 新增顾客
const handleAdd = () => {
  customerForm.value = {
    name: '',
    idNumber: '',
    work: '',
    occupation: '',
    travelId: undefined
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await customerApi.addCustomer(customerForm.value)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('添加失败')
      }
    }
  })
}

// 添加处理分页改变的方法
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

// 添加新的响应式数据
const popoverVisible = ref(false)
const travelSearchKey = ref('')
const selectedTravelName = computed(() => {
  const selected = routeOptions.value.find(
    option => option.travelId === customerForm.value.travelId
  )
  return selected?.routeName || ''
})

// 添加过滤后的旅游选项计算属性
const filteredTravelOptions = computed(() => {
  if (!travelSearchKey.value) return routeOptions.value
  return routeOptions.value.filter(option =>
    option.routeName.toLowerCase().includes(travelSearchKey.value.toLowerCase())
  )
})

// 选择旅游信息的方法
const selectTravel = (option: TravelMessageVo) => {
  customerForm.value.travelId = option.travelId
  popoverVisible.value = false
}

onMounted(() => {
  fetchData()
  fetchRouteOptions()
})
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 164px);
  padding-bottom: 100px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.custom-form {
  padding: 20px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

.route-option {
  padding: 10px;
}

.route-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.route-name {
  font-weight: bold;
  font-size: 14px;
}

.route-detail {
  display: flex;
  gap: 8px;
  align-items: center;
}

.route-time {
  font-size: 12px;
  color: #666;
}

.route-message {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  line-height: 1.5;
}

.guide-level {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

:deep(.el-table) {
  margin: 20px;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select) {
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 0 20px 40px;
}

.travel-options {
  padding: 10px;
}

.travel-search {
  margin-bottom: 10px;
}

.travel-list {
  max-height: 200px;
  overflow-y: auto;
}

.travel-item {
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.travel-item:hover {
  background-color: #f5f7fa;
}

.travel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.travel-name {
  font-weight: bold;
}

.travel-info-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.travel-spots {
  margin-top: 5px;
}

.label {
  font-weight: bold;
}

.content {
  margin-left: 5px;
}

.guide-tag {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.travel-selector {
  width: 100%;
}

.travel-info-popover {
  padding: 10px;
}

/* 添加新的样式 */
.travel-selector {
  cursor: pointer;
}

.travel-options {
  max-height: 400px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.travel-search {
  padding: 0 0 8px;
  border-bottom: 1px solid #eee;
}

.travel-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.travel-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.travel-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.travel-item.is-selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.travel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.travel-name {
  font-weight: bold;
  font-size: 14px;
}

.travel-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.travel-time {
  font-size: 12px;
  color: #666;
}

.travel-spots {
  font-size: 12px;
  line-height: 1.5;
}

.travel-spots .label {
  color: #666;
}

.travel-spots .content {
  color: #333;
}

.guide-tag {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

:deep(.travel-info-popover) {
  padding: 16px;
  max-width: 90vw;
}
</style> 